from coin.exchange.base.kr_rest.product import NativeProduct, NormProduct
from coin.exchange.base.kr_rest.futures_product import NativeFuturesProduct
from coin.exchange.shared.kr_rest.constants import quote_currency_list
from coin.exchange.shared.kr_rest.currency import SharedCurrency


class SharedProduct(NativeProduct):
  _exchange = "Shared"
  NativeCurrencyType = SharedCurrency

  def __init__(self, base, quote):
    assert isinstance(base, SharedCurrency), base
    assert isinstance(quote, SharedCurrency), base
    native_symbol = "%s-%s" % (base.native_currency, quote.native_currency)
    NativeProduct.__init__(self, base, quote, native_symbol)

  @classmethod
  def FromStrNativeProductImpl(cls, product, current_datetime):
    assert isinstance(product, str), (type(product), product)
    if "-" in product:
      pair = product.split("-")
      assert len(pair) == 2
      base = SharedCurrency.FromStrNativeCurrency(pair[0])
      quote = SharedCurrency.FromStrNativeCurrency(pair[1])
      assert base.currency is not None  # cannot check base_curerncy_list
      assert quote.currency in quote_currency_list
      return cls(base, quote)
    else:
      for quote in quote_currency_list:
        if product.endswith(quote):
          base = SharedCurrency.FromStrNativeCurrency(product[:-len(quote)])
          quote = SharedCurrency.FromStrNativeCurrency(quote)
          return SharedProduct(base, quote)
      raise ValueError("Unable to parse: %s" % (product,))


class SharedFuturesProduct(NativeFuturesProduct):
  _exchange = "Shared"
  NativeCurrencyType = SharedCurrency

  def __init__(self, base, quote, expiry):
    NativeFuturesProduct.__init__(self,
                                  base,
                                  quote,
                                  expiry,
                                  "%s-%s.%s" % (base.currency, quote.currency, expiry))

  @staticmethod
  def FromProduct(cls, product):
    assert isinstance(product, NormFuturesProduct), type(product)
    return SharedFuturesProduct(product.base, product.quote, product.expiry)

  @classmethod
  def FromStr(cls, product):
    assert type(product) == str
    if "-" in product:
      ret = product.split(".")
      assert len(ret) == 2
      ret2 = ret[0].split("-")
      assert len(ret2) == 2
      return SharedFuturesProduct(SharedCurrency.FromStr(ret2[0]),
                                  SharedCurrency.FromStr(ret2[1]),
                                  ret[1])
    else:
      assert "-" in product, product
